package com.swg.wxorder.service.impl;

import com.swg.wxorder.dto.OrderDTO;
import com.swg.wxorder.enums.PayStatusEnum;
import com.swg.wxorder.enums.ResultEnum;
import com.swg.wxorder.exception.SellException;
import com.swg.wxorder.service.BuyerService;
import com.swg.wxorder.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author 【swg】.
 * @Date 2018/6/23 16:56
 * @DESC
 * @CONTACT 317758022@qq.com
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService{
    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderid) {
        OrderDTO orderDTO = checkOrderOwner(openid,orderid);
        return orderDTO;
    }

    @Override
    public OrderDTO cancleOrder(String openid, String orderid) {
        OrderDTO orderDTO = checkOrderOwner(openid,orderid);
        if(orderDTO == null){
            log.error("【取消订单】查不到改订单, orderId={}", orderid);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    @Override
    public OrderDTO payOrder(String openid, String orderid) {
        OrderDTO orderDTO = checkOrderOwner(openid,orderid);
        if(orderDTO==null){
            log.error("【支付订单】查不到改订单, orderId={}", orderid);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        if(!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())){
            log.error("【支付订单】订单状态不对,orderId={}",orderid);
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        return orderService.paid(orderDTO);
    }

    @Override
    public OrderDTO finishOrder(String openid, String orderid) {
        OrderDTO orderDTO = checkOrderOwner(openid,orderid);
        if(orderDTO==null){
            log.error("【完结订单】查不到改订单, orderId={}", orderid);
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.finish(orderDTO);
    }

    private OrderDTO checkOrderOwner(String openid, String orderId){
        if(StringUtils.isEmpty(openid) || StringUtils.isEmpty(orderId)){
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        OrderDTO orderDTO = orderService.findOne(orderId);
        if(orderDTO == null){
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        if(!openid.equalsIgnoreCase(orderDTO.getBuyerOpenid())){
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
